
const imageInput = document.getElementById("imageInput");
const modelInput = document.getElementById("modelInput");
const imageInfo = document.getElementById("imageInfo");
const modelInfo = document.getElementById("modelInfo");
const uploadedImage = document.getElementById("uploadedImage");
const submitModel = document.getElementById("submitModel")
submitModel.addEventListener("click", function (event) {
    // 绑定事件
    upload(imageInput.files,modelInput.files);
});
imageInput.addEventListener("change", function (event) {
    displayFileInfo(event.target.files, imageInfo);
    displayUploadedImages(event.target.files, uploadedImage);
});

modelInput.addEventListener("change", function (event) {
    displayFileInfo(event.target.files, modelInfo);
});

//上传图片
function upload(imgFiles,modelFiles){
    const formData = new FormData();
    for (let i = 0; i < modelFiles.length; i++) {
        const modelFile = modelFiles[i];
        formData.append('model', modelFile);
        formData.append('modelFileName', modelFile.name);
    }
    for (let i = 0; i < imgFiles.length; i++) {
        const imgFile = imgFiles[i];
        //创建FormData
        formData.append('images', imgFile);
        formData.append('imgFileNames', imgFile.name);
    }
    // 发送 AJAX 请求
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:8080/upload", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 请求成功，处理后端响应
                const responseData = xhr.responseText;
                alert(responseData); // 弹窗显示后端返回的信息
            } else {
                // 请求失败
                console.error('Error:', xhr.status);
            }
        }
    };
    xhr.send(formData);
}
// 展示图片信息
function displayFileInfo(files, infoElement) {
    infoElement.innerHTML = "";
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileItem = document.createElement("div");
        fileItem.textContent = `文件名: ${file.name}, 大小: ${formatFileSize(
            file.size
        )}`;
        infoElement.appendChild(fileItem);
    }
}

// #展示已上传的图片
function displayUploadedImages(files, imageElement) {
    if (files && files.length > 0) {
        const reader = new FileReader();
        reader.onload = function (e) {
            imageElement.src = e.target.result;
        };
        reader.readAsDataURL(files[0]);
    } else {
        imageElement.src = "";
    }
}

function formatFileSize(bytes) {
    const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    if (bytes === 0) return "0 Byte";
    const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + " " + sizes[i];
}
